package api

import (
	"fmt"
	"net/http"
	"strings"

	"gitee.com/go-course/go12/devcloud-mini/cmdb/apps/secret"
	restfulspec "github.com/emicklei/go-restful-openapi/v2"
	"github.com/emicklei/go-restful/v3"
	"github.com/gorilla/websocket"
	"github.com/infraboard/mcube/http/label"
	"github.com/infraboard/mcube/ioc"
	"github.com/infraboard/mcube/ioc/config/logger"
	"github.com/rs/zerolog"
)

func init() {
	ioc.Api().Registry(&handler{})
}

type handler struct {
	controller secret.Service
	log        *zerolog.Logger
	ioc.ObjectImpl
}

func (h *handler) Init() error {
	h.log = logger.Sub(secret.AppName)
	h.controller = ioc.GetController(secret.AppName).(secret.Service)
	return nil
}

func (h *handler) Name() string {
	return secret.AppName
}

func (h *handler) Version() string {
	return "v1"
}

func (h *handler) Upgrader() *websocket.Upgrader {
	return &websocket.Upgrader{
		ReadBufferSize:  4096,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			if r.Method != "GET" {
				fmt.Println("method is not GET")
				return false
			}
			// 在你api 的路径里面 明确这是一个socket api
			// localhost:8080/cmdb/api/v1/secret/ws/sycnresource
			if !strings.Contains(r.URL.Path, "/ws") {
				fmt.Println("path error")
				return false
			}
			return true
		},
	}
}

func (h *handler) Registry(ws *restful.WebService) {
	tags := []string{"云商凭证管理"}
	ws.Route(ws.GET("/").To(h.ListSecret).
		Doc("云商凭证列表").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		// 开启认证
		Metadata(label.Auth, label.Enable).
		// 开启鉴权
		Metadata(label.Permission, label.Enable).
		// 开启审计
		Metadata(label.Audit, label.Enable).
		// 路由装饰 丰富路由信息 注册信息
		Metadata(label.Resource, "secrets").
		Metadata(label.Action, "list"))

	ws.Route(ws.GET("/{id}").To(h.DescribeSecret).
		Doc("云商凭证详情").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		// 开启认证
		Metadata(label.Auth, label.Enable).
		// 开启鉴权
		Metadata(label.Permission, label.Enable).
		// 路由装饰 丰富路由信息 注册信息
		Metadata(label.Resource, "secrets").
		Metadata(label.Action, "get"))

	ws.Route(ws.POST("/").To(h.CreateSecret).
		Doc("创建云商凭证").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		// 开启认证
		Metadata(label.Auth, label.Enable).
		// 开启鉴权
		Metadata(label.Permission, label.Enable).
		Metadata(label.Resource, "secrets").
		Metadata(label.Action, "create"))

	// websocket 资源同步
	ws.Route(ws.GET("/ws/{id}/sync_resource").To(h.SyncResource).
		Doc("资源同步Websocket").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		// 路由装饰 丰富路由信息 注册信息
		Metadata(label.Resource, "secret").
		Metadata(label.Action, "sync resource"))
}
